/* 
 *  Incub - incubate your baby robot
 *  Copyright (C) 2008 Stanislaw Szymczyk
 *  e-mail: sszymczy@gmail.com   www: http://cogville.cog-lab.com
 *
 *  This file is part of Incub.
 *
 *  Incub is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Incub is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Incub.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
 
#include <iostream>
#include <vector>
#include "boost/program_options.hpp"

using std::vector;
namespace po = boost::program_options;

#include "incubate.h"

REF_CLASS_DEFINE(AngularVelocimeter);
REF_CLASS_DEFINE(BallJoint);
REF_CLASS_DEFINE(Box);
REF_CLASS_DEFINE(Camera);
REF_CLASS_DEFINE(Capsule);
REF_CLASS_DEFINE(Cylinder);
REF_CLASS_DEFINE(Entity);
REF_CLASS_DEFINE(FixedJoint);
REF_CLASS_DEFINE(HingeJoint);
REF_CLASS_DEFINE(Joint);
REF_CLASS_DEFINE(Light);
REF_CLASS_DEFINE(LinearVelocimeter);
REF_CLASS_DEFINE(Material)
REF_CLASS_DEFINE(Motor);
REF_CLASS_DEFINE(VelocityControlledMotor);
REF_CLASS_DEFINE(TorqueControlledMotor);
REF_CLASS_DEFINE(Plane);
REF_CLASS_DEFINE(PositionSensor);
REF_CLASS_DEFINE(Sensor);
REF_CLASS_DEFINE(Shape);
REF_CLASS_DEFINE(Sphere);
REF_CLASS_DEFINE(TactileMatrix);
REF_CLASS_DEFINE(TactileSensor);
REF_CLASS_DEFINE(Transformable);
REF_CLASS_DEFINE(UniversalJoint);
REF_CLASS_DEFINE(World);

#include "Renderer.h"
#include "Physics.h"
#include "Corba.h"

void preprocessEntity(World* world, Entity* entity) {
	vector<Shape*>& shapes = entity->getShapes();
	for(vector<Shape*>::iterator shape = shapes.begin(); shape != shapes.end(); shape++) {
		Material *mat;
		try {
			mat = world->getMaterial((*shape)->getMaterialName());
		} catch(Material::NoSuchMaterialException& ex) {
			std::cerr << ex.what() << std::endl;
			mat = world->getMaterial(Material::getDefaultName());
		}
		(*shape)->setMaterial(mat);
		(*shape)->setEntity(entity);	
	}
	vector<Sensor*>& sensors = entity->getSensors();
	for(vector<Sensor*>::iterator sensor = sensors.begin(); sensor != sensors.end(); sensor++) {
		if(dynamic_cast<TactileMatrix*>(*sensor)) {
			TactileMatrix *matrix = dynamic_cast<TactileMatrix*>(*sensor);
			if(matrix->getShapeIndex() != 0) {
				// shape-based TactileMatrix, we have to create sensors
				Shape *shape = shapes[matrix->getShapeIndex()-1];
				Vector3D position = shape->getPosition();
				Quaternion rotation = shape->getRotation();
				matrix->setShape(shape);
				Tactile *tactileShape = dynamic_cast<Tactile*>(shape);
				tactileShape->createSensors(matrix);
				vector<TactileSensor*>& tactileSensors = matrix->getSensors();
				for(vector<TactileSensor*>::iterator tactileSensor = tactileSensors.begin(); tactileSensor != tactileSensors.end(); tactileSensor++) {
					Sphere *sensorShape = new SphereImpl();
					sensorShape->setRadius(matrix->getTouchResolution());
					sensorShape->setPosition(Vector3D((*tactileSensor)->getX(), (*tactileSensor)->getY(), (*tactileSensor)->getZ()));
					sensorShape->setMaterial(shape->getMaterial());
					Vector3D localPosRot = rotation * sensorShape->getPosition();
					sensorShape->setPosition(position + localPosRot);
					sensorShape->setRotation(rotation * sensorShape->getRotation());
					entity->addShape(sensorShape);
					(*tactileSensor)->setShapeIndex(shapes.size());
					(*tactileSensor)->setShape(sensorShape);
				}					
			} else {
				// ordinary TactileMatrix, just init the sensors
				vector<TactileSensor*> sensors = matrix->getSensors();
				for(vector<TactileSensor*>::iterator sensor = sensors.begin(); sensor != sensors.end(); sensor++) {
					Shape *sensorShape = shapes[(*sensor)->getShapeIndex()-1];
					(*sensor)->setShape(sensorShape);
					(*sensor)->setX(sensorShape->getX());
					(*sensor)->setY(sensorShape->getY());
					(*sensor)->setZ(sensorShape->getZ());
				}
			}
		}
	}	
	vector<Joint*>& joints = entity->getJoints();
	for(vector<Joint*>::iterator joint = joints.begin(); joint != joints.end(); joint++) {
		preprocessEntity(world, (*joint)->getEntity());
	}
}

void step() {
	Physics::step();
	Renderer::idle();
	Corba::step();	
};

int main(int argc, char **argv) {
	ticpp::Document *doc;
	xml::Xmlable *root;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "produce help message")
		("file,f", po::value<std::string>(), "specification file")	    
	;
	
	po::positional_options_description p;
	p.add("file", -1);
	
	po::variables_map vm;
	
	try {
		po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
		po::notify(vm);	
		
		if (vm.count("help") || !vm.count("file")) {
		    std::cout << desc << "\n";
		    return 1;
		}

		doc = new ticpp::Document( vm["file"].as<std::string>());
		doc->LoadFile();
		root = xml::genesis(doc->FirstChildElement());
		World *world = dynamic_cast<xml::XmlWorld*>(root)->_type;
		
		vector<Entity*>& entities = world->getEntities();
		Material* def_mat = new MaterialImpl();
		world->addMaterial(def_mat);
		for(vector<Entity*>::iterator entity = entities.begin(); entity != entities.end(); entity++) {
			preprocessEntity(world, *entity);
		}
		Physics::init(world);
		Corba::init(argc, argv, world);
		Renderer::init(argc, argv, world, &step);
		Renderer::render_all();
	} catch( ticpp::Exception& ex ) {
		std::cerr << ex.what() << std::endl;
		exit(1);	
	} catch( xml::Xmlable::Exception& ex) {
		std::cerr << ex.what() << std::endl;
		exit(1);	
	} catch( Renderer::RendererException& ex) {
		std::cerr << ex.what() << std::endl;
		exit(1);	
	} catch( Corba::CorbaException& ex) {
		std::cerr << ex.what() << std::endl;
		exit(1);	
	} catch( po::unknown_option& ex) {
		std::cerr << ex.what() << std::endl;
		exit(1);	
	} catch( ExitException& ex) {
		std::cout << "exiting..." << std::endl;
		Renderer::cleanup();
		Corba::cleanup();
		Physics::cleanup();
		delete dynamic_cast<xml::XmlWorld*>(root)->_type;
		xml::Xmlable::cleanup();
		delete doc;
	}
	return 0;
}
